import { isArray } from "@/utils/is";
import { FieldNamesProps } from "@/components/ProTable/interface";
import { downloadLink } from "@/api/modules/upload";
import { ElMessage } from "element-plus";

/**
 * @description 获取localStorage
 * @param {String} key Storage名称
 * @returns {String}
 */
export function localGet(key: string) {
  const value = window.localStorage.getItem(key);
  try {
    return JSON.parse(window.localStorage.getItem(key) as string);
  } catch (error) {
    return value;
  }
}

/**
 * @description 存储localStorage
 * @param {String} key Storage名称
 * @param {*} value Storage值
 * @returns {void}
 */
export function localSet(key: string, value: any) {
  window.localStorage.setItem(key, JSON.stringify(value));
}

/**
 * @description 清除localStorage
 * @param {String} key Storage名称
 * @returns {void}
 */
export function localRemove(key: string) {
  window.localStorage.removeItem(key);
}

/**
 * @description 清除所有localStorage
 * @returns {void}
 */
export function localClear() {
  window.localStorage.clear();
}

/**
 * @description 判断数据类型
 * @param {*} val 需要判断类型的数据
 * @returns {String}
 */
export function isType(val: any) {
  if (val === null) return "null";
  if (typeof val !== "object") return typeof val;
  else return Object.prototype.toString.call(val).slice(8, -1).toLocaleLowerCase();
}

/**
 * @description 生成唯一 uuid
 * @returns {String}
 */
export function generateUUID() {
  let uuid = "";
  for (let i = 0; i < 32; i++) {
    let random = (Math.random() * 16) | 0;
    if (i === 8 || i === 12 || i === 16 || i === 20) uuid += "-";
    uuid += (i === 12 ? 4 : i === 16 ? (random & 3) | 8 : random).toString(16);
  }
  return uuid;
}

/**
 * 判断两个对象是否相同
 * @param {Object} a 要比较的对象一
 * @param {Object} b 要比较的对象二
 * @returns {Boolean} 相同返回 true，反之 false
 */
export function isObjectValueEqual(a: { [key: string]: any }, b: { [key: string]: any }) {
  if (!a || !b) return false;
  let aProps = Object.getOwnPropertyNames(a);
  let bProps = Object.getOwnPropertyNames(b);
  if (aProps.length != bProps.length) return false;
  for (let i = 0; i < aProps.length; i++) {
    let propName = aProps[i];
    let propA = a[propName];
    let propB = b[propName];
    if (!b.hasOwnProperty(propName)) return false;
    if (propA instanceof Object) {
      if (!isObjectValueEqual(propA, propB)) return false;
    } else if (propA !== propB) {
      return false;
    }
  }
  return true;
}

/**
 * @description 生成随机数
 * @param {Number} min 最小值
 * @param {Number} max 最大值
 * @returns {Number}
 */
export function randomNum(min: number, max: number): number {
  let num = Math.floor(Math.random() * (min - max) + max);
  return num;
}

/**
 * @description 获取当前时间对应的提示语
 * @returns {String}
 */
export function getTimeState() {
  let timeNow = new Date();
  let hours = timeNow.getHours();
  if (hours >= 6 && hours <= 10) return `早上好 ⛅`;
  if (hours >= 10 && hours <= 14) return `中午好 🌞`;
  if (hours >= 14 && hours <= 18) return `下午好 🌞`;
  if (hours >= 18 && hours <= 24) return `晚上好 🌛`;
  if (hours >= 0 && hours <= 6) return `凌晨好 🌛`;
}

/**
 * @description 获取浏览器默认语言
 * @returns {String}
 */
export function getBrowserLang() {
  let browserLang = navigator.language ? navigator.language : navigator.browserLanguage;
  let defaultBrowserLang = "";
  if (["cn", "zh", "zh-cn"].includes(browserLang.toLowerCase())) {
    defaultBrowserLang = "zh";
  } else {
    defaultBrowserLang = "en";
  }
  return defaultBrowserLang;
}

/**
 * @description 使用递归扁平化菜单，方便添加动态路由
 * @param {Array} menuList 菜单列表
 * @returns {Array}
 */
export function getFlatMenuList(menuList: Menu.MenuOptions[]): Menu.MenuOptions[] {
  let newMenuList: Menu.MenuOptions[] = JSON.parse(JSON.stringify(menuList));
  return newMenuList.flatMap(item => [item, ...(item.children ? getFlatMenuList(item.children) : [])]);
}

/**
 * @description 使用递归过滤出需要渲染在左侧菜单的列表 (需剔除 isHide == true 的菜单)
 * @param {Array} menuList 菜单列表
 * @returns {Array}
 * */
export function getShowMenuList(menuList: Menu.MenuOptions[]) {
  let newMenuList: Menu.MenuOptions[] = JSON.parse(JSON.stringify(menuList));
  return newMenuList.filter(item => {
    item.children?.length && (item.children = getShowMenuList(item.children));
    return !item.meta?.isHide;
  });
}

/**
 * @description 使用递归找出所有面包屑存储到 pinia/vuex 中
 * @param {Array} menuList 菜单列表
 * @param {Array} parent 父级菜单
 * @param {Object} result 处理后的结果
 * @returns {Object}
 */
export const getAllBreadcrumbList = (menuList: Menu.MenuOptions[], parent = [], result: { [key: string]: any } = {}) => {
  for (const item of menuList) {
    result[item.path] = [...parent, item];
    if (item.children) getAllBreadcrumbList(item.children, result[item.path], result);
  }
  return result;
};

/**
 * @description 使用递归处理路由菜单 path，生成一维数组 (第一版本地路由鉴权会用到，该函数暂未使用)
 * @param {Array} menuList 所有菜单列表
 * @param {Array} menuPathArr 菜单地址的一维数组 ['**','**']
 * @returns {Array}
 */
export function getMenuListPath(menuList: Menu.MenuOptions[], menuPathArr: string[] = []): string[] {
  for (const item of menuList) {
    if (typeof item === "object" && item.path) menuPathArr.push(item.path);
    if (item.children?.length) getMenuListPath(item.children, menuPathArr);
  }
  return menuPathArr;
}

/**
 * @description 递归查询当前 path 所对应的菜单对象 (该函数暂未使用)
 * @param {Array} menuList 菜单列表
 * @param {String} path 当前访问地址
 * @returns {Object | null}
 */
export function findMenuByPath(menuList: Menu.MenuOptions[], path: string): Menu.MenuOptions | null {
  for (const item of menuList) {
    if (item.path === path) return item;
    if (item.children) {
      const res = findMenuByPath(item.children, path);
      if (res) return res;
    }
  }
  return null;
}

/**
 * @description 使用递归过滤需要缓存的菜单 name (该函数暂未使用)
 * @param {Array} menuList 所有菜单列表
 * @param {Array} keepAliveNameArr 缓存的菜单 name ['**','**']
 * @returns {Array}
 * */
export function getKeepAliveRouterName(menuList: Menu.MenuOptions[], keepAliveNameArr: string[] = []) {
  menuList.forEach(item => {
    item.meta.isKeepAlive && item.name && keepAliveNameArr.push(item.name);
    item.children?.length && getKeepAliveRouterName(item.children, keepAliveNameArr);
  });
  return keepAliveNameArr;
}

/**
 * @description 格式化表格单元格默认值 (el-table-column)
 * @param {Number} row 行
 * @param {Number} col 列
 * @param {*} callValue 当前单元格值
 * @returns {String}
 * */
export function formatTableColumn(row: number, col: number, callValue: any) {
  // 如果当前值为数组，使用 / 拼接（根据需求自定义）
  if (isArray(callValue)) return callValue.length ? callValue.join(" / ") : "--";
  return callValue ?? "--";
}

/**
 * @description 处理值无数据情况
 * @param {*} callValue 需要处理的值
 * @returns {String}
 * */
export function formatValue(callValue: any) {
  // 如果当前值为数组，使用 / 拼接（根据需求自定义）
  if (isArray(callValue)) return callValue.length ? callValue.join(" / ") : "--";
  return callValue ?? "--";
}

/**
 * @description 处理 prop 为多级嵌套的情况，返回的数据 (列如: prop: user.name)
 * @param {Object} row 当前行数据
 * @param {String} prop 当前 prop
 * @returns {*}
 * */
export function handleRowAccordingToProp(row: { [key: string]: any }, prop: string) {
  if (!prop.includes(".")) return row[prop] ?? "--";
  prop.split(".").forEach(item => (row = row[item] ?? "--"));
  return row;
}

/**
 * @description 处理 prop，当 prop 为多级嵌套时 ==> 返回最后一级 prop
 * @param {String} prop 当前 prop
 * @returns {String}
 * */
export function handleProp(prop: string) {
  const propArr = prop.split(".");
  if (propArr.length == 1) return prop;
  return propArr[propArr.length - 1];
}

/**
 * @description 根据枚举列表查询当需要的数据（如果指定了 label 和 value 的 key值，会自动识别格式化）
 * @param {String} callValue 当前单元格值
 * @param {Array} enumData 字典列表
 * @param {Array} fieldNames label && value && children 的 key 值
 * @param {String} type 过滤类型（目前只有 tag）
 * @returns {String}
 * */
export function filterEnum(callValue: any, enumData?: any, fieldNames?: FieldNamesProps, type?: "tag") {
  const value = fieldNames?.value ?? "value";
  const label = fieldNames?.label ?? "label";
  const children = fieldNames?.children ?? "children";
  let filterData: { [key: string]: any } = {};
  // 判断 enumData 是否为数组
  if (Array.isArray(enumData)) filterData = findItemNested(enumData, callValue, value, children);
  // 判断是否输出的结果为 tag 类型
  if (type == "tag") {
    return filterData?.tagType ? filterData.tagType : "";
  } else {
    return filterData ? filterData[label] : "--";
  }
}

/**
 * @description 递归查找 callValue 对应的 enum 值
 * */
export function findItemNested(enumData: any, callValue: any, value: string, children: string) {
  return enumData.reduce((accumulator: any, current: any) => {
    if (accumulator) return accumulator;
    if (current[value] === callValue) return current;
    if (current[children]) return findItemNested(current[children], callValue, value, children);
  }, null);
}

/**
 * @param items
 * @returns
 */
export function arrayToTree(items) {
  let res = []; // 存放结果集
  let map = {};
  // 判断对象是否有某个属性
  let getHasOwnProperty = (obj, property) => Object.prototype.hasOwnProperty.call(obj, property);

  // 边做map存储，边找对应关系
  for (const i of items) {
    map[i.id] = {
      ...i,
      children: getHasOwnProperty(map, i.id) ? map[i.id].children : []
    };
    const newItem = map[i.id];
    if (!i.parentId) {
      res.push(newItem);
    } else {
      if (!getHasOwnProperty(map, i.parentId)) {
        map[i.parentId] = {
          children: []
        };
      }
      map[i.parentId].children.push(newItem);
    }
  }
  return res;
}

/**
 * @param list
 * @param parent
 * @returns
 */
export function listToTree(list, parent) {
  const out = [];
  for (let node of list) {
    if (node.parentId == parent) {
      // 递归
      let children = listToTree(list, node.id);
      if (children.length) {
        node.children = children;
      }
      out.push(node);
    }
  }
  return out;
}
/**
 * 菜单品拼接
 */
export function getMenuList(list: any, parent?: any) {
  const out = [];
  for (let node of list) {
    if (node.parentId == parent) {
      // 转换字段值
      let item: any = {
        path: node.url,
        name: node.componentName,
        component: node.component,
        redirect: node.redirect,
        meta: {
          icon: node.icon,
          title: node.name,
          activeMenu: node.activeMenu,
          isLink: node.isLink,
          isHide: node.isHide,
          isFull: node.isFull,
          isAffix: node.isAffix,
          isKeepAlive: node.isKeepAlive
        }
      };
      // 递归
      let children = getMenuList(list, node.id);
      if (children.length) {
        //node.children = children;
        item.children = children;
      }
      out.push(item);
    }
  }
  return out;
}

/**
 * 下载
 */

export function downFiles(blob: Blob, filename: string, callBack: () => void) {
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, filename);
  } else {
    const anchor = document.createElement("a");
    const body = document.querySelector("body");
    anchor.href = window.URL.createObjectURL(blob);
    anchor.download = filename;
    anchor.style.display = "none";
    body.appendChild(anchor);
    anchor.click();
    body.removeChild(anchor);
    window.URL.revokeObjectURL(anchor.href);
    if (callBack && typeof callBack == "function") {
      callBack();
    }
  }
}

// 跳转下载
export const downFilesOpen = async (filePath: string, fileName: string) => {
  const data = await downloadLink({
    filePath,
    fileName
  });
  let a = document.createElement("a");
  a.style = "display: none"; // 创建一个隐藏的a标签
  a.download = fileName;
  a.href = data;
  document.body.appendChild(a);
  a.click(); // 触发a标签的click事件
  document.body.removeChild(a);
};

export const customSetInterval = (callback: Function, delay: number) => {
  let shouldRun = true;
  let timeoutId;
  if (typeof callback === "function") {
    callback();
  }
  const loop = () => {
    if (shouldRun) {
      callback();
      timeoutId = setTimeout(loop, delay);
    }
  };
  timeoutId = setTimeout(loop, delay);
  return {
    cancel: function () {
      shouldRun = false;
      clearTimeout(timeoutId);
    }
  };
};

export const addEvent = (element: HTMLElement, type: string, callback: () => void) => {
  if (element.addEventListener) {
    element.addEventListener(type, callback, false);
  } else if ((element as any).attachEvent) {
    (element as any).attachEvent("on" + type, callback);
  } else {
    (element as any)["on" + type] = callback;
  }
};

// 查找父节点
export const findParent: any = (nodes: any, targetNode: String) => {
  for (const node of nodes) {
    if (node.children && node.children.length > 0) {
      const found = findParent(node.children, targetNode);
      if (found) return found;
    }
    if (node.id === targetNode) {
      return node;
    }
  }
  return null;
};

// 查找当前节点
export const getCurrentNode: any = (data, key) => {
  let temp = null;
  for (let i = 0; i < data.length; i++) {
    if (data[i].id === key) {
      return data[i];
    } else if (data[i].children?.length) {
      const o = getCurrentNode(data[i].children, key);
      if (o) return o;
    }
  }
  return temp;
};
// 数组对象取并集
export const unionByProperty = (arr1, arr2, property) => {
  const combined = arr1.concat(arr2);
  const map = new Map();

  return combined.filter(item => {
    if (!map.has(item[property])) {
      map.set(item[property], true);
      return true;
    }
    return false;
  });
};

// 数组对象差集
export const differenceByProperty = (arr1, arr2, property) => {
  return arr1.filter(item1 => !arr2.some(item2 => item2[property] === item1[property]));
};

/**
 * 转换文件的大小带单位
 * @param size 文件大小
 * @returns string
 */
export function convertFileSizeUnit(size = 0) {
  if (size == 0) return "0 B";

  if (size < 1024) {
    return `${size} B`; // 小于1KB
  } else if (size < 1024 * 1024) {
    return `${(size / 1024).toFixed(2)} KB`; // 小于1MB
  } else if (size < 1024 * 1024 * 1024) {
    return `${(size / (1024 * 1024)).toFixed(2)} MB`; // 小于1GB
  } else {
    return `${(size / (1024 * 1024 * 1024)).toFixed(2)} GB`; // 大于等于1GB
  }
}

/**
 * 根据文件流转成的 blob 下载文件
 * @param blob 文件 blob
 * @param filename 文件名
 */
export function downloadFileByBlob(blob: Blob, filename: string) {
  const href = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.style.display = "none";
  a.href = href;
  a.download = filename;
  a.rel = "noopener noreferrer";
  document.body.append(a);
  a.click();
  URL.revokeObjectURL(href); //释放URL对象
  a.remove();
}

/**
 * 判断视频编码格式
 */

export const checkVideoFormat = (fileItem: any) => {
  const file = fileItem.raw;
  if (!file.type.includes("video/mp4")) return;
  // 创建MP4解析器实例
  return new Promise((resolve, reject) => {
    let mp4box = MP4Box.createFile();
    mp4box.onError = function (e: any) {
      console.log(e);
    };

    // 定义视频加载完毕后的回调函数
    mp4box.onReady = function (info: any) {
      console.log("info", info);

      // 判断方式一
      if (info.mime.includes("avc")) {
        console.log("此mp4为H264");
        resolve(true);
      } else {
        console.log("此mp4为H265");
        reject(false);
      }
    };
    let reader = new FileReader();
    reader.onload = function (e: any) {
      console.log(e);
      let arraybuffer: any = e.target.result;
      arraybuffer.fileStart = 0;
      mp4box.appendBuffer(arraybuffer);
      mp4box.flush();
    };
    reader.readAsArrayBuffer(file);
  });
};

export const userNameHandler = (userName: string) => {
  return userName || "该用户已注销";
};

/**
 * 下载复制剪贴板
 */

export const copyToClipboard = async (filePath: string, fileName: string) => {
  const link: any = await downloadLink({
    filePath,
    fileName
  });
  const input = document.createElement("input");
  input.value = link;
  document.body.appendChild(input);
  input.select();
  document.execCommand("Copy");
  document.body.removeChild(input);
  ElMessage({
    type: "success",
    message: "复制成功"
  });
};
